package edu.uaskl.jqf.tools;

/**
 * Stops the watch. Lazy time to do time measurements.
 * 
 * @author tbach
 */

public class StopWatch {
    private final String name;
    private final long timeStart;
    private long timeLastTick;

    public StopWatch() {
        this("");
    }

    public StopWatch(final String name) {
        if (!name.isEmpty()) // also throws NPE -tbach
            System.out.println("stopwatch start: " + name);
        this.name = name;
        timeStart = System.currentTimeMillis();
        timeLastTick = timeStart;
    }

    public long tick() {
        return tick("");
    }

    public long tick(final String message) {
        final long timeNow = System.currentTimeMillis();
        System.out.println(new StringBuilder(message.length() + 50).append("stopwatch  tick: ").append(message).append(message.isEmpty() ? "" : " - ")
                .append("took: ").append(timeNow - timeLastTick).append(" ms."));
        timeLastTick = System.currentTimeMillis();
        return timeLastTick;
    }

    public long tickQuiet() {
        timeLastTick = System.currentTimeMillis();
        return timeLastTick;
    }

    public long stop() {
        return stop("");
    }

    public long stop(final String message) {
        final long timeNow = System.currentTimeMillis();
        tick(message);
        System.out.println(new StringBuilder(name.length() + 50).append("stopwatch   end: ").append(name).append(name.isEmpty() ? "" : " - ")
                .append("took total: ").append(timeNow - timeStart).append(" ms."));
        timeLastTick = System.currentTimeMillis();
        return timeLastTick;
    }
}
